/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CMSContentPanel.java
 *
 * Created on May 16, 2011, 6:26:30 PM
 */
package com.tecnick.jxhtmledit;

import java.awt.BorderLayout;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.BoxLayout;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author Jay
 */
public class CMSContentPanel extends javax.swing.JPanel {

    ArrayList<ContentRow> payload_triplets;

    /** Creates new form CMSContentPanel */
    public CMSContentPanel() {
        initComponents();
        this.ResultsPanel.setLayout(new BoxLayout(this.ResultsPanel, BoxLayout.Y_AXIS));
        ArrayList<String[]> payload_triplets_tmp = new ArrayList<String[]>();
        payload_triplets = new ArrayList<ContentRow>();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        ResultsPanel = new javax.swing.JPanel();
        InitSearchButton = new javax.swing.JButton();
        SearchQueryTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        ResultsPanel.setLayout(new javax.swing.BoxLayout(ResultsPanel, javax.swing.BoxLayout.LINE_AXIS));
        jScrollPane1.setViewportView(ResultsPanel);

        InitSearchButton.setText("Search");
        InitSearchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                InitSearchButtonActionPerformed(evt);
            }
        });

        SearchQueryTextField.setColumns(15);

        jLabel1.setText("Search:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(SearchQueryTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(InitSearchButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(SearchQueryTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(InitSearchButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void InitSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InitSearchButtonActionPerformed
        String query = this.SearchQueryTextField.getText();
        if (query.length() <= 0) {
            JOptionPane.showMessageDialog(this, "The search field is empty.", "Error", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String[] queryparts = query.split(" ");
        ArrayList<ContentRow> matches = new ArrayList<ContentRow>();
        ArrayList<String[]> raws = new ArrayList<String[]>();
        CMSDatabaseInterface cdi = new CMSDatabaseInterface();
        try {
            raws = cdi.getContentList(queryparts);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "Cannot complete query. CMS data layer may be inactive.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        //this.SearchQueryTextField.setText(raws.size() + " rows affected");
        for (String[] s : raws) {
            matches.add(new ContentRow(s[0], s[1], s[2], s[3]));
        }
        for (ContentRow c : matches) {
            c.score = getMatchScore(c, queryparts);
        }

        Collections.sort(matches);


        ResultsPanel.removeAll();
        for (ContentRow c : matches) {
            JPanel j = new JPanel(new BorderLayout());

            JLabel Name = new JLabel(c.Name);
            JLabel Descr;
            if (c.Descr.length() < 21) {
                Descr = new JLabel(c.Descr);
            } else {
                Descr = new JLabel(c.Descr.substring(0, 21));
            }
			String Tag = c.Tag;
			String NewTag = Tag.substring(0, Tag.length() - 2);
            String Payload = "<" + NewTag + " id=\"" + c.ID + "\">";
            //
            j.add(Name, BorderLayout.WEST);
            j.add(Descr, BorderLayout.CENTER);
            CMSJLabelDragSource NameDragSource = new CMSJLabelDragSource(Name, Payload);
            CMSJLabelDragSource DescrDragSource = new CMSJLabelDragSource(Descr, Payload);
            j.setSize(j.getPreferredSize());
            ResultsPanel.add(j);
            ResultsPanel.revalidate();
        }

    }//GEN-LAST:event_InitSearchButtonActionPerformed

    private int getMatchScore(ContentRow cr, String[] query) {
        int score = 0;

        for (String s : query) {
            score += count(cr.Name, s);
            score += count(cr.ID, s);
            score += count(cr.Descr, s);
        }
        return score;
    }

    public static int count(String string, String substring) {
        int count = 0;
        int idx = 0;
        String dupe = string.toLowerCase();
        String subdupe = substring.toLowerCase();
        while ((idx = dupe.indexOf(subdupe, idx)) != -1) {
            idx++;
            count++;
        }

        return count;
    }

    private class ContentRow implements Comparable {

        String Name;
        String Descr;
        String ID;
        int score;
		String Tag;

        public ContentRow(String name, String descr, String id, String tag) {
            Name = name;
            Descr = descr;
            ID = id;
            score = 0;
            Tag = tag;
        }

        public int compareTo(Object o) {
            if (o instanceof ContentRow) {
                ContentRow c = (ContentRow) o;
                if (c.score > this.score) {
                    return -1;
                } else if (c.score < this.score) {
                    return 1;
                }
                return 0;
            }
            throw new java.lang.IllegalArgumentException("Content Row cannot be compared to this");
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton InitSearchButton;
    private javax.swing.JPanel ResultsPanel;
    private javax.swing.JTextField SearchQueryTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
